<template>
  <div>
    <h1>这是手机验证码登录</h1>
    <el-form :model="phoneForm" :rules="rules" ref="phoneLoginRef">
      <el-form-item prop="phone">
        <el-input placeholder="请输入手机号" prefix-icon="el-icon-phone" v-model="phoneForm.phone"></el-input>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="17">
          <el-form-item prop="code">
            <el-input placeholder="请输入验证码" prefix-icon="el-icon-tickets" v-model="phoneForm.code"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item>
            <el-button type="warning" @click="getCode" :disabled="disabled">{{btnText}}</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button class="submit-btn" type="warning" @click="submit">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
    name: 'PhoneLogin',
    props: {
        phoneForm: {
            type: Object,
            required: true
        },
        rules: {
            type: Object,
            required: true
        },
        ptime: {
            type: Number,
            required: false,
            default: 60
        }
    },
    created() {
        this.time = this.$props.ptime
    },
    data() {
        return {
            btnText: '获取验证码',
            disabled: false,
            time: null
        }
    },
    methods: {
        getCode() {
            let reg = /^1[3|5|7|8][0-9]{9}$/
            this.$refs.phoneLoginRef.validateField('phone', (value)=>{
                console.log(value)
                if(!value) {
                    if(reg.test(this.phoneForm.phone)){
                        /* 获得验证码，进入倒计时 */
                        let timer = setInterval(()=>{
                            this.time--
                            this.disabled = true
                            this.btnText = `${this.time}s后重新获取`
                            if(this.time === 0) {
                                this.disabled = false
                                this.btnText = '重新获取'
                                clearInterval(timer)
                            }
                        },1000)
                    }else {
                        this.$message.error('手机号格式有误！')
                    }
                }
            })

        },
        submit() {
            this.$refs.phoneLoginRef.validate((value)=> {
                if(!value) {
                    this.$message.error('登录失败！')
                }else {
                    this.$emit('phoneLogin')
                }
            })
        }
    }
};
</script>

<style lang="scss" scoped>
.submit-btn {
    width: 100%;
}
</style>